﻿#include "cuserlogin.h"
#include "ui_cuserlogin.h"
#include <QPainter>
#include "common/common.h"

QString CUserLogin::s_token;

CUserLogin::CUserLogin(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CUserLogin)
{
    ui->setupUi(this);
    m_pHttpMgr = new QNetworkAccessManager(this);
    initUI();
}

CUserLogin::~CUserLogin()
{
    delete ui;
}

void CUserLogin::paintEvent(QPaintEvent * ev)
{
    Q_UNUSED(ev)
    QPixmap pixmap(":/res/user_login_backgroup.png"); // 加载图片
    QPainter painter(this);
    // 调整图片大小以适应窗口大小，同时保持宽高比
    pixmap = pixmap.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    painter.drawPixmap(this->rect(), pixmap); // 在整个窗口区域绘制图片
}

void CUserLogin::initUI()
{
    setWindowTitle("VVClass用户登录");
    //填充QComboBox
    QStringList slist;
    slist<<"+86 中国(China)"<<"+852 香港(Hong Kong)";
    ui->comboBox->insertItems(0,slist);

    //设置只能输电话号码
    ui->lineEdit_phone_number->setInputMask("000-0000-0000");

    setStyleSheet();

    // 设置窗口的初始大小，或者根据需要调整
    // this->resize(1920, 1080);
}

void CUserLogin::setStyleSheet()
{
    //设置标题栏
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);

}
void CUserLogin::SendPostRequst(const QString& strhead,QByteArray arr)
{
    QString url = "http://cs8.hyzyt.cn/user/passwordLogin" + strhead;
    QNetworkRequest _quest;
    _quest.setUrl((QUrl(url)));
    qDebug()<<url;
    _quest.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));

    mReply = m_pHttpMgr->post(_quest,arr);
    connect(mReply,&QNetworkReply::finished,this,[=]{
        ReplyFinshed();
    });
}
void CUserLogin::ReplyFinshed()
{
    if (mReply->error() == QNetworkReply::NoError)
    {
        // 处理返回的数据
        QByteArray _data = mReply->readAll();//读出数据
        QJsonDocument doc = QJsonDocument::fromJson(_data);
        if (doc.isNull())
        {
            qDebug() << "Failed to parse JSON.";
            return;
        }
        QJsonObject   obj = doc.object();
        s_token = obj.value("data").toObject().value("token").toString();
        qDebug()<<_data;
    }
    else
    {
        // 处理错误
        qDebug()<<"error ==> "<<mReply->error();
    }
    mReply->deleteLater();
}
void CUserLogin::on_pushButton_login_clicked()
{
    bool ret =  true;
    QJsonObject rawJson;


    // 测试 手机号已经可区分教师和学生
    //rawJson["phone"] = "18674495122"; // 学生手机号
    rawJson["phone"] = "18169445678"; // 教师手机号

    rawJson["password"] = "zyt123"; // 替换为你的密码
    rawJson["area_code"] = "+86";

    //设置为json格式数据
    QByteArray byte_array = QJsonDocument(rawJson).toJson();
    SendPostRequst(POST_USER_LOGIN,byte_array);
    if(ret)
    {
        this->hide();
        m_pMainWnd = new MainWindow();
        m_pMainWnd->show();
    }
}

QString CUserLogin::getToken()
{
    return s_token;
}
